package thread;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {
    private long time;
    // 实际任务要执行的代码
    private Runnable runnable;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    private Thread t = null;
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask tast = new MyTimerTask(runnable, delay);
            queue.offer(tast);
            // 添加新的元素后,就可以唤醒扫描线程的wait了
            locker.notify();
        }
    }

    public void cancle() {
        t.interrupt();
    }

    //构造方法,创建扫描线程
    public MyTimer() {
        t = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                //引入锁目的是保证队列在多线程下的是安全的
                // 把锁放到while里面, 才有释放锁的机会, 外面才有可能释放锁
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        //获取当前时间
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            //当前时间已经达到了任务的执行时间
                            queue.poll();
                            task.run();
                        } else {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        });

        t.start();
    }
}

public class ThreadDemo31 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);

        System.out.println("hello main");

        Thread.sleep(5000);
        timer.cancle();
    }
}



















